package org.wk.common.qiniu;

import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;

import java.io.IOException;


public class ClientBuilder {

    public static String ACCESS_KEY = "RvbcPYK1NQsmAxRbUkRQ5r_bifR5QHULegXyBWit";
    public static String SECRET_KEY = "b7SX-V7fo8IjfB6P76o6eqmI4ZRGzinsgWP0LIdS";

    private static Auth auth;

    private static Configuration configuration;

    private static BucketManager bucketManager;

    private static UploadManager uploadManager;

    private ClientBuilder() {
        // do nothing
    }

    protected static synchronized Auth createAuth() {
        if(auth == null){
            auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        }
        return auth;
    }

    /**
     * 七牛云授权
     * @param bucket
     * @return
     */
    public static String token(String bucket) {
        return createAuth().uploadToken(bucket);
    }

    protected static synchronized Configuration createConfiguration() {
        if(configuration == null){
            /**
             * 华东	Zone.zone0()
             * 华北	Zone.zone1()
             * 华南	Zone.zone2()
             * 北美	Zone.zoneNa0()
             */
            configuration = new Configuration(Zone.zone1());
        }
        return configuration;
    }

    protected static synchronized BucketManager createBucketManager() {
        if(bucketManager == null){
            bucketManager = new BucketManager(createAuth(), createConfiguration());
        }
        return bucketManager;
    }

    /**
     * 普通上传
     * @return
     */
    public static synchronized UploadManager createUploadManager() {
        if(uploadManager == null){
            uploadManager = new UploadManager(createConfiguration());
        }
        return uploadManager;
    }

    /**
     * 断点续传
     * @param localTempDir 本地临时文件目录
     * @return
     * @throws IOException
     */
    protected static UploadManager createRecorderUploadManager(String localTempDir) throws IOException {
        // FileRecorder 设置断点续传文件进度保存目录
        return new UploadManager(createConfiguration(), new FileRecorder(localTempDir));
    }

}
